﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Manage_EditUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //string uid = Request.Params["uid"];
            //CmsDataContext db = new CmsDataContext();
            //var q1 = from aR in db.Role
            //         orderby aR.Authority
            //         select aR;
            //UserPowers.DataSource = q1.ToList();
            //UserPowers.DataValueField = "ID";
            //UserPowers.DataTextField = "Name";
            //UserPowers.DataBind();

            //var q2 = from aM in db.Manager
            //        where aM.ID == uid
            //        select aM;

            //if (q2.Count() != 0)
            //{
            //    Manager m = q2.First();
            //    UserID.Text = m.ID;
            //    UserID.ReadOnly = true;
            //    UserName.Text = m.Name;

            //    List<string> q3 = (from aP in db.Power
            //                       where aP.ManagerID == uid
            //                       select aP.RoleID).ToList(); ;
            //    foreach (ListItem l in UserPowers.Items)
            //    {
            //        l.Selected = q3.Contains(l.Value);
            //    }
            //}
        }
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        string uid = UserID.Text.Trim();
        string uname = UserName.Text.Trim();

        CmsDataContext db = new CmsDataContext();

        try
        {
            Manager m;
            var q = from aM in db.Manager where aM.ID == uid select aM;

            #region 先处理用户信息
            if (UserID.ReadOnly)
            {
                //更新用户信息
                m = q.First();
                m.Name = uname;
            }
            else
            {
                //新增用户信息，先看看数据有没有数据
                if (q.Count() > 0)
                {
                    MessageBox.Message = "用户名已经存在。";
                    return;
                }

                m = new Manager();
                m.ID = uid;
                m.Name = uname;
                m.Password = "123456";

                db.Manager.InsertOnSubmit(m);
            }
            #endregion

            #region 处理权限信息
            //先删除用户已经的权限
            var q2 = from aP in db.Power
                     where aP.ManagerID == uid
                     select aP;
            db.Power.DeleteAllOnSubmit(q2);            
            #endregion

            db.SubmitChanges();

            MessageBox.Message = "用户信息保存成功。";
            MessageBox.Location = "./EditUser.aspx?uid=" + uid;
        }
        catch
        {
            MessageBox.Message = "保存用户信息时发生错误。";
        }
    }
}